<?php
// +----------------------------------------------------------------------
// | Created by Sublime: [ Conqweal ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021~20223[chenjia] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.99dn.cn
// +----------------------------------------------------------------------
// | Author: Conqweal <150672834@qq.com>
// +----------------------------------------------------------------------
// | Date: 2021/12/22 0026
// +----------------------------------------------------------------------
// | Description:会员接口
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\Api;
use app\api\library\Ems;
 
use app\api\library\Credit;
use app\api\model\UserCredit as creditModel;
use app\api\model\UserCreditLog as creditLogModel;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Validate;
use app\ApiController;
use support\Request;
use Webman\Captcha\CaptchaBuilder;
class UserController extends ApiController
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','verifyExist'];
    protected $noNeedRight = '*';

    

    /**
     * 会员中心
     */
    public function index()
    {
        return $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {

        $account  = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->response->cookie('login_fail', $this->request->cookie('login_fail') + 1);
            return $this->error(__('Invalid parameters'));
        }
        //防止暴力破解
        if ($this->request->cookie('login_fail') > 10) {
            return $this->error(__('Invalid parameters'));
        }


        $ret = $this->auth->login($account, $password);

        if ($ret) {
            $info          = $this->auth->getUserinfo();           
            $data['token'] = $info['token'];
            $this->response->cookie('login_fail', 0);
             //登录日志
            Db::name('user_login')->insert(
                [
                    'u_id'=>$info['u_id'],
                    'create_time'=>time(),
                    'ip'=>get_client_ip(),
                ]
            );

            //信用分当月
            $month_data = monthBeginAndEnd();
            $w=[];
            $w[] = ['u_id','=',$info['u_id']];
            $w[] = ['create_time','between',implode(',',$month_data)];
            $t = Db::name('user_login')->where($w)->count();
            if($t>10){               
                Credit::sceneLog($info['u_id'], 'month_login10',['uk'=>date('Y-m')]);
            }
 
            return $this->success(__('Logged in successful'), $data);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email    = $this->request->post('email');
        $phone    = $this->request->post('phone');
        $code     = $this->request->post('code');
        $nickname = $this->request->post('nickname');
        $captcha  = $this->request->post('captcha');
        if (!$username || !$password) {
            return $this->error(__('Invalid parameters'));
        }
        if(strlen($username)<3){
             return $this->error(__('tooshortusername'));
        }
         if(strlen($password)<6){
             return $this->error(__('Invalid parameters'));
        }


        if (!$this->captcha_check()) {
            return $this->error(__('captcha is incorrect'));
        };

        if ($email && !Validate::is($email, "email")) {
            return $this->error(__('Email is incorrect'));
        }

       

        $ret = $this->auth->register($username, $password, $email, $phone, ['nickname' => $nickname]);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            return $this->success(__('Sign up successful'), $data);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    private function captcha_check(){
        // 获取post请求中的captcha字段
        $captcha = $this->request->post('captcha');
        // 对比session中的captcha值
        if (strtolower($captcha) !== $this->request->session()->get('captcha')) {
            return false;
        }
        return true;
    }
 


    /**
     * 验证用户是否存在
     * @return [type] [description]
     */
    public function verifyExist(){
          $username = $this->request->post('username');
          $email = $this->request->post('email');          
          $email_code = $this->request->post('email_code');          
          $merge = $this->request->post('merge/d',0);          
          $f = 1;
          if($username){            
              $f = Db::name("user")->where("username",$username)->count();
             
          } 
          if($email){            
              $f = Db::name("user")->where("email",$email)->count();              
          }

          if($email_code){            
            $ret = Ems::check($email, $email_code, 'resetpwd');
            $f = $ret ? 1:0;
          }


          if($merge){
             $f = Db::name("user")->where("username",$username)->where("email",$email)->count();
          }

          $data=['exists'=>$f>0?1:0];
          return $this->success(__('Operation successful'), $data);  
    }




    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            return $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        return $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function changeProfile()
    {
        $post         = $this->request->post();
        $user         = $this->auth->getUser();
        $username     = $this->request->post('username');
        $nickname     = $this->request->post('nickname');
        $phone        = $this->request->post('phone');
        $email        = $this->request->post('email');
        $old_password = $this->request->post('old_password');
        $password     = $this->request->post('password');
        $bio          = $this->request->post('bio');
        $bank_info    = $this->request->post('bank_info');
        $msn          = $this->request->post('msn');
        $jobs         = $this->request->post('jobs');
        $sex          = $this->request->post('sex');
        $truename     = $this->request->post('truename');
        $intro        = $this->request->post('intro');
        $birthday     = $this->request->post('birthday');
        $address      = $this->request->post('address');
        $avatar       = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        
        if ($username) {
            $exists = \app\api\model\User::where('username', $username)->where('u_id', '<>', $this->auth->u_id)->find();
            if ($exists) {
                return $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\api\model\User::where('nickname', $nickname)->where('u_id', '<>', $this->auth->u_id)->find();
            if ($exists) {
                return $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }

        if ($old_password) {
            if ($user->password != $this->auth->getEncryptPassword($old_password, $user->salt)) {
                return $this->error(__('The original password is incorrect'));

            }
            $password && $user->password = $this->auth->getEncryptPassword($password, $user->salt);

        }

        if ($email) {
            $exists = \app\api\model\User::where('email', $email)->where('u_id', '<>', $this->auth->u_id)->find();
            if ($exists) {
                return $this->error(__('Email already exist'));
            }

            $ex                  = \app\api\model\UserAuthen::where('auth_type', 1)->where('u_id', $this->auth->u_id)->find();
            !$ex && $user->email = $email;
        }
        isset($post['bio']) && $user->bio     = $bio;
        isset($post['sex']) && $user->sex     = $sex;
        isset($post['phone']) && $user->phone = $phone;

        $profile                                           = [];
        isset($post['birthday']) && $profile['birthday']   = $birthday;
        isset($post['truename']) && $profile['truename']   = $truename;
        isset($post['msn']) && $profile['msn']             = $msn;
        isset($post['bank_info']) && $profile['bank_info'] = $bank_info;
        isset($post['jobs']) && $profile['jobs']           = $jobs;
        isset($post['avatar']) && $profile['avatar']       = $avatar;
        isset($post['address']) && $profile['address']     = $address;
        isset($post['intro']) && $profile['intro']         = $intro;

        if (empty($user->profile)) {
            $profile['u_id'] = $this->auth->u_id;
            \app\api\model\UserProfile::create($profile);
            $user->save();
        } else {
            if ($profile) {
                $user->together(['profile' => $profile])->save();
            } else {
                $user->save();
            }
        }
        //信用分处理
        $post['truename'] && \app\api\library\Credit::sceneLog($this->auth->u_id,'profile_truename');
        $post['phone'] && \app\api\library\Credit::sceneLog($this->auth->u_id,'profile_mobile');       
        count($post)>9 &&   \app\api\library\Credit::sceneLog($this->auth->u_id,'profile_complete');
       

        return $this->success(__('Update ok'));
    }

    /**
     * 获取用户资料
     * @param  [type] $token [登录token]
     * @return [type]        [json数据]
     */
    public function profile($token)
    {

        $user            = $this->auth->getUser();
      //  $user['profile'] = $user->profile;
      //  $authens         = $user->authens;
     
      //  $user['authens'] = array_column($authens, null, 'auth_type');
        $user['credit'] = Db::name("user_credit")->where('u_id',$this->auth->u_id)->find();
        $user['credit'] && $user['credit']['credit_level_txt'] = __(\app\api\model\UserCredit::creditLevel($user['credit']['level'])[0]);

        $user['stats']   = [
            'mission_created'      => Db::name("mission")->alias("a")->join("mission_description b","a.mission_id=b.mission_id and b.language_id=".$this->lang_id)->where('a.u_id', $this->auth->u_id)->count(),
            'mission_involved'     => Db::name("mission_schedule")->alias("a")->join("mission_description b","a.mission_id=b.mission_id and b.language_id=".$this->lang_id)->where('u_id', $this->auth->u_id)->count(),
            'mission_involved_win' => Db::name("mission_schedule")->alias("a")->join("mission_description b","a.mission_id=b.mission_id and b.language_id=".$this->lang_id)->where('u_id', $this->auth->u_id)->where('status', 3)->count(),
        ];
      
        return $this->success(__('Operation successful'), ['userData' => $user]);
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user    = $this->auth->getUser();
        $email   = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            return $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            return $this->error(__('Email is incorrect'));
        }
        if (\app\api\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            return $this->error(__('Email already exist'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            return $this->error(__('Captcha is incorrect'));
        }
        $verification        = $user->verification;
        $verification->email = 1;
        $user->verification  = $verification;
        $user->email         = $email;
        $user->save();
        Ems::flush($email, 'changeemail');
        return $this->success();
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */

    public function resetpwd()
    {
        $type        = $this->request->post("type");
        $email       = $this->request->post("email");
        $username       = $this->request->post("username");
        $newpassword = $this->request->post("newpassword");
        $captcha     = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            return $this->error(__('Invalid parameters'));
        }
        if ($type == 'email') {
            if (!Validate::is($email, "email")) {
                return $this->error(__('Email is incorrect'));
            }
            if(!$username){
                  return $this->error(__('Username can not be empty'));
            }
            
            $user = \app\api\model\User::getByEmail($email);
            if (!$user) {
                return $this->error(__('User not found'));
            }
            if($user->username!=$username){
                 return $this->error(__('username error'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                return $this->error(__('Captcha is incorrect'));
            } else {
                Ems::flush($email, 'resetpwd');
            }
        }
        //模拟一次登录
        $this->auth->direct($user->u_id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            return $this->success(__('Reset password successful'));
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */

    public function emailVerify()
    {

        $email = $this->request->post("email");

        $captcha = $this->request->post("captcha");
        if (!$captcha) {
            return $this->error(__('Invalid parameters'));
        }

        if (!Validate::is($email, "email")) {
            return $this->error(__('Email is incorrect'));
        }
        $user = \app\api\model\User::getByEmail($email);
        if (!$user) {
            return $this->error(__('User not found'));
        }
        $ret = Ems::check($email, $captcha, 'authen');
        if (!$ret) {
            return $this->error(__('Captcha is incorrect'));
        } else {
            Ems::flush($email, 'authen');
        }

        $model = new \app\api\model\UserAuthen;
        $f     = $model->where('u_id', $this->auth->u_id)->where('auth_type', 1)->find();
        if ($f) {
            return $this->error(__('email verifyed already'));
        } else {
            $model->save([
                'u_id'         => $this->auth->u_id,
                'auth_type'    => 1,
                'auth_content' => [
                    'email'   => $email,
                    'captcha' => $captcha
                    ,
                ],
            ]);
        }
        if ($ret) {
            //信用分处理
            \app\api\library\Credit::sceneLog($this->auth->u_id,'profile_email_vetify');
            return $this->success(__('Operation successful'));
        } else {
            return $this->error(__('Operation failed'));
        }
    }


 
     /**
      * 信用分明细
      * @return [type] [description]
      */
     public function creditLogData(){
        $request =request();
        $limit = $request->get("limit",10);
        $q = creditLogModel::alias("a")
        ->join("user b"," a.u_id=b.u_id")
        ->join("user_profile p"," p.u_id=a.u_id","left");       
        $q->where('a.u_id',$this->auth->u_id);        
        $request->get('type') && $q->where('a.type',$request->get('type'));        
        $q->order("id","desc");
        $ls    = $q->field("a.*,b.username,p.avatar")->paginate(['list_rows' => $limit, 'request' => request()->all()]); 
        $total = $ls->total();
        $types = creditModel::creditBasic();  
        $items = $ls->items();      
        $items = array_map(function($v)use($types){
            $v->type_txt = $types[$v->type][0]; 
            return $v;
        }, $items);   
        return json(['code' => $total > 0 ? 0 : 201, 'msg' => '无数据', 'count' => $total, 'data' => $items]);
    }


}
